package com.cn.ZhiKeDianShang.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.base.BaseActivity;
import com.cn.ZhiKeDianShang.model.event.updateDeclarationBean;
import com.cn.ZhiKeDianShang.model.response.BlList;
import com.cn.ZhiKeDianShang.model.response.StateAndTeamBean;
import com.cn.ZhiKeDianShang.model.response.UserInfoBean;
import com.cn.ZhiKeDianShang.model.response.getTeamBean;
import com.cn.ZhiKeDianShang.presenter.LoginUserPresenter;
import com.cn.ZhiKeDianShang.presenter.view.LoginUserView;
import com.cn.ZhiKeDianShang.util.TimeSelect.CustomTeamAndStatePicker;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/7/3.
 * do what to 2017/7/3
 */

public class AddDeclarationActivity extends BaseActivity<LoginUserView, LoginUserPresenter> implements LoginUserView {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_nickname)
    TextView tvTeam;
    @BindView(R.id.et_number)
    TextView etNumber;
    @BindView(R.id.et_remark)
    TextView etRemark;
    @BindView(R.id.tv_add)
    TextView tvAdd;


    //   true 为添加操作  false为修改操作
    boolean isAdd;
    //选择 团队或是状态值 弹窗传过去的数据
    List<StateAndTeamBean> mList = new ArrayList<>();
    //选择的团队id
    String teamid;
    //数量
    String num;
    //备注
    String remark;
    BlList.BdBean dateBean;
    int position;

    @Override
    protected int getNormalLayoutId() {
        return R.layout.activity_add_declaration;
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.activity_add_declaration;
    }

    @Override
    protected LoginUserPresenter createPresenter() {
        return new LoginUserPresenter(this, this);
    }

    @Override
    protected void initViewsAndEvents() {
        isAdd = getIntent().getBooleanExtra("isAdd", false);
        dateBean = (BlList.BdBean) getIntent().getSerializableExtra("dateBean");
        position = getIntent().getIntExtra("position", 0);

        if (isAdd) {
            tvTitle.setText("添加报单");
            tvAdd.setText("提交");
        } else {
            tvTitle.setText("修改报单");
            tvAdd.setText("修改");
        }
        if (dateBean != null) {
            teamid = dateBean.getAid() + "";
            tvTeam.setText(dateBean.getNickname() + "");
            num = dateBean.getNum() + "";
            etNumber.setText(dateBean.getNum() + "");
            remark = dateBean.getRemark() + "";
            if (!TextUtils.isEmpty(dateBean.getRemark())) {
                etRemark.setText(dateBean.getRemark() + "");
            }
        }
    }


    /**
     * 获取关联团队
     */
    private void getTeam() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.ORDER_RELATETEAM)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<getTeamBean>(getTeamBean.class) {
                    @Override
                    public void onResponse(ObjectResult<getTeamBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(AddDeclarationActivity.this, result)) {
                            if (mList.size() > 0) {
                                mList.clear();
                            }
                            getTeamBean data = result.getData();
                            for (int i = 0; i < data.getTeams().size(); i++) {
                                getTeamBean.TeamsBean teamsBean = data.getTeams().get(i);
                                mList.add(new StateAndTeamBean(teamsBean.getAid(), teamsBean.getNickname()));
                            }
                            TeamAndStatePicker(true, tvTeam.getText().toString(), mList);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    /**
     * 添加 编辑 报单
     */
    private void addAndUpdate() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        params.put("aid", teamid);
        params.put("num", num);
        params.put("remark", remark);
        String url = "";
        if (isAdd) {
            url = AppConfig.BD_ADD;
        } else {
            if (dateBean != null) {
                params.put("id", dateBean.getId() + "");
            }
            url = AppConfig.BD_EDIT;
        }

        HttpUtils.post().url(url)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<getTeamBean>(getTeamBean.class) {
                    @Override
                    public void onResponse(ObjectResult<getTeamBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        if (Result.checkSuccess(AddDeclarationActivity.this, result)) {
                            ToastUtil.showShort(result.getResultMsg());
                            if (isAdd) {
                                EventBus.getDefault().post(new updateDeclarationBean(1));
                            } else {
                                dateBean.setAid(teamid + "");
                                dateBean.setNickname(tvTeam.getText().toString());
                                dateBean.setNum(etNumber.getText().toString());
                                dateBean.setRemark(etRemark.getText().toString());
                                EventBus.getDefault().post(new updateDeclarationBean(2, position, dateBean));
                            }
                            finish();
                        }

                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    CustomTeamAndStatePicker customTeamAndStatePicker;

    /**
     * 关联团队 以及任务状态
     */
    private void TeamAndStatePicker(boolean isSelectTeam, String selestText, List<StateAndTeamBean> data) {
        //获取当前时间
        //tvElectricalTime.setText(now.split(" ")[0]);
        Log.d("Debug", "传过来的 data为" + data.size());
        customTeamAndStatePicker = new CustomTeamAndStatePicker(AddDeclarationActivity.this, isSelectTeam, selestText, data, new CustomTeamAndStatePicker.ResultHandler() {
            @Override
            public void handle(String aid, String nickname, boolean isSelectTeam) {
                if (isSelectTeam) {
                    tvTeam.setText(nickname);
                    teamid = aid;
                }

            }
        }); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customTeamAndStatePicker.setIsLoop(); // 设置控件循环滚动 （这个在方法里面设置 相应控件能不能循环滑动）
        customTeamAndStatePicker.show("");

    }


    @Override
    public void onLogin(UserInfoBean resultBean) {

    }

    @Override
    public void requestFailed(String message) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.setting_back, R.id.rl_updatenickname, R.id.tv_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setting_back:
                finish();
                break;
            case R.id.rl_updatenickname:
                getTeam();
                break;
            case R.id.tv_add:
                if (TextUtils.isEmpty(teamid)) {
                    ToastUtil.showShort("请选择团队");
                    return;
                }
                num = etNumber.getText().toString();
                if (TextUtils.isEmpty(num)) {
                    ToastUtil.showShort("请输入数量");
                    return;
                }
                remark = etRemark.getText().toString();
                addAndUpdate();
                break;
        }
    }
}
